/**
 * 
 */
package br.edu.ufcg.embedded.eolica.view;

import java.io.IOException;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/**
 * This class are responsable for the splash screen
 * 
 * @author maurilio
 * 
 */
public class SplashScreen extends Canvas implements Runnable {

	Image image;
	String title;
	Displayable next;
	int timeout;
	Display d;

	public SplashScreen(String title, Display d, Displayable next) {
		this.title = title;
		this.next = next;
		timeout = 0;
		image = null;
		this.d = d;
		setFullScreenMode(true);
	}

	public void setTimeOut(int timeout) {
		this.timeout = timeout;
	}

	public void setImage(String url) {
		try {
			image = Image.createImage(url);
		} catch (IOException e) {
			e.printStackTrace();
			image = null;
		}
	}

	protected void paint(Graphics g) {
		g.setColor(0xffffff);
		g.fillRect(0, 0, getWidth(), getHeight());

		if (image != null) {
			g.drawImage(image, getWidth() / 2, getHeight() / 2,
					Graphics.VCENTER | Graphics.HCENTER);
		}

		if (title != null) {
			g.setColor(0x000000);
			g.drawString(title, 5, 5, Graphics.LEFT | Graphics.TOP);
		}
	}

	public void start() {
		d.setCurrent(this);
		new Thread(this).start();
	}

	public void run() {
		if (timeout == 0)
			timeout = 1000;

		// update the screen
		repaint();
		serviceRepaints();

		// wait a litle time
		try {
			Thread.sleep(timeout);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		// show the next screen
		d.setCurrent(next);
	}

}
